import smtplib
import email,os,time
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email import encoders
from email.header import Header

def send_code_email(content_text,title = ""):

    attfile = r'E:\python\code_test\code.jpg'
    cookie_file = r'E:\python\code_test\code_c'
    success = r'E:\python\code_test\success'
    date = time.strftime("%Y%m%d")

    if len(content_text) == 0:
        content_text = "打卡邮件，请回复"
    
    if len(title) == 0 :
        send_title = '上班打卡[DAKA]'+ date
    else:
        send_title = title

    if os.path.exists(success):
        os.remove(success)

    # if os.path.exists(attfile):
    #     os.remove(attfile)

    if os.path.exists(cookie_file):
        os.remove(cookie_file)

    msg = MIMEMultipart()
    
    msg['Subject'] = Header(send_title, 'gb18030')
    msg['From'] = "{0}<qianchengdaka@126.com>".format(Header("qianchengdaka", 'gbk'))
    msg['To'] =  "{0}<qianchengdaka@126.com>".format(Header("qianchengdaka", 'gbk'))
    content1 = MIMEText(content_text, 'plain', 'gbk')
    msg.attach(content1)

    # while(1):
    #     if(os.path.exists(attfile) is False):
    #         cookie_test.collect_cookie_code()
    #         time.sleep(5)
    #     else:
    #         break;


    basename = os.path.basename(attfile)
    fp = open(attfile, 'rb')
    att = MIMEText(fp.read(), 'base64', 'gbk')
    att["Content-Type"] = 'application/octet-stream'
    att.add_header('Content-Disposition', 'attachment',filename=('gbk', '', basename))
    encoders.encode_base64(att)
    msg.attach(att)
    fp.close()
    smtpObj = smtplib.SMTP()
    smtpObj.connect(host="smtp.126.com",port=25)
    smtpObj.login("qianchengdaka@126.com","huang8121801")
    smtpObj.sendmail("qianchengdaka@126.com",["qianchengdaka@126.com"],msg.as_string())
    smtpObj.close()
    print("发送打卡邮件\n")



send_code_email("xxx","xxx")